package com.ruoyi.syf.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.syf.domain.RiskCheckTask;
import com.ruoyi.syf.domain.vo.RiskCheckTaskVo;
import com.ruoyi.syf.handler.task.TaskFactory;
import com.ruoyi.syf.task.config.CronTaskRegistrar;
import com.ruoyi.syf.task.config.SchedulingRunnable;
import com.ruoyi.syf.task.enttity.ScheduleSetting;
import com.ruoyi.syf.task.mapper.ScheduleSettingMapper;
import com.ruoyi.syf.task.service.ScheduleSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class ScheduleSettingServiceImpl extends ServiceImpl<ScheduleSettingMapper, ScheduleSetting> implements ScheduleSettingService {

    @Resource
    private CronTaskRegistrar cronTaskRegistrar;
    @Autowired
    private TaskFactory taskFactory;

    @Override
    public void addCheckTask(RiskCheckTaskVo vo) throws IllegalAccessException {
        addCheckTask(vo,false);
    }

    @Override
    public <T extends RiskCheckTask> void addCheckTask(T vo, boolean status) throws IllegalAccessException {
        //转换cron表达式
        String cron = taskFactory.toCronExpression(
                vo.getCycleType(),
                vo.getCycle(),
                vo.getCycleUnit(),
                vo.getActualStartTime());
        ScheduleSetting scheduleSetting = new ScheduleSetting();
        scheduleSetting.setBeanName("CheckTask");
        scheduleSetting.setMethodName("taskSaveRecord");
        scheduleSetting.setMethodParams(vo.getId().toString());
        scheduleSetting.setRemark(vo.getId().toString());
        scheduleSetting.setCron(cron);
        scheduleSetting.setStatus(vo.getStatus());
        add(scheduleSetting,status);
    }

    @Override
    public void updateCheckTask(RiskCheckTaskVo riskCheckTaskVo) throws IllegalAccessException {
        ScheduleSetting scheduleSetting = getOne(
                new LambdaQueryWrapper<ScheduleSetting>()
                        .eq(ScheduleSetting::getRemark, riskCheckTaskVo.getId().toString()));
        if (scheduleSetting == null){
            addCheckTask(riskCheckTaskVo);
            return;
        }
        //转换cron表达式
        String cron = taskFactory.toCronExpression(
                riskCheckTaskVo.getCycleType(),
                riskCheckTaskVo.getCycle(),
                riskCheckTaskVo.getCycleUnit(),
                riskCheckTaskVo.getActualStartTime());
        scheduleSetting.setCron(cron);
        scheduleSetting.setStatus(riskCheckTaskVo.getStatus());
        update(scheduleSetting,false);
    }
//
//    @Override
//    public boolean addRealTimeDataTask(Integer cycle) {
//        ScheduleSetting scheduleSetting = new ScheduleSetting();
//        scheduleSetting.setBeanName("RealTimeDataTask");
//        scheduleSetting.setMethodName("getRealTimeData");
//        scheduleSetting.setCron(String.format("0 */%s * * * ?",cycle));
//        scheduleSetting.setStatus(true);
//        scheduleSetting.setRemark("实时数据");
//        return add(scheduleSetting,true);
//    }
//
//    @Override
//    public boolean updateRealTimeDataTask(Integer cycle) {
//        ScheduleSetting scheduleSetting = getOne(new LambdaQueryWrapper<ScheduleSetting>()
//                .eq(ScheduleSetting::getBeanName,"RealTimeDataTask")
//                .eq(ScheduleSetting::getMethodName,"getRealTimeData")
//                .eq(ScheduleSetting::getRemark,"实时数据"));
//        scheduleSetting.setCron(String.format("0 */%s * * * ?",cycle));
//        return update(scheduleSetting,true);
//    }

    @Override
    public boolean add(ScheduleSetting scheduleSetting, boolean isChanges) {
//        scheduleSetting.setCreateTime(new Date());
//        scheduleSetting.setUpdateTime(new Date());
        boolean save = save(scheduleSetting);
        if (!save) {
            log.error("添加定时任务失败,任务id：{}，备注：{}", scheduleSetting.getId(), scheduleSetting.getRemark());
            return false;
        } else {
            if (isChanges && scheduleSetting.getStatus()) {// 添加成功,并且状态是1，直接放入任务器
                SchedulingRunnable task = new SchedulingRunnable(
                        scheduleSetting.getBeanName(),
                        scheduleSetting.getMethodName(),
                        scheduleSetting.getMethodParams());
                cronTaskRegistrar.addCronTask(task, scheduleSetting.getCron());
            }
        }
        return true;
    }

    @Override
    public boolean update(ScheduleSetting scheduleSetting, boolean isChanges) {
        // 查询修改前任务
        ScheduleSetting existedSysJob = getById(scheduleSetting.getId());
        // 修改任务
//        scheduleSetting.setCreateTime(new Date());
//        scheduleSetting.setUpdateTime(new Date());
        boolean update = updateById(scheduleSetting);
        if (!update) {
            log.error("修改定时任务失败,任务id：{}，备注：{}", scheduleSetting.getId(), scheduleSetting.getRemark());
            return false;
        } else {
            // 修改成功,则先删除任务器中的任务,并重新添加
            SchedulingRunnable oldTask = new SchedulingRunnable(
                    existedSysJob.getBeanName(),
                    existedSysJob.getMethodName(),
                    existedSysJob.getMethodParams());
            cronTaskRegistrar.removeCronTask(oldTask);
            if (isChanges && scheduleSetting.getStatus()) {// 如果修改后的任务状态是1就加入任务器
                SchedulingRunnable task = new SchedulingRunnable(
                        scheduleSetting.getBeanName(),
                        scheduleSetting.getMethodName(),
                        scheduleSetting.getMethodParams());
                cronTaskRegistrar.addCronTask(task, scheduleSetting.getCron());
            }
        }
        return true;
    }

    @Override
    public boolean del(Long id) {
        // 先查询要删除的任务信息
        ScheduleSetting existedSysJob = getById(id);
        // 删除
        boolean del = removeById(id);
        if (!del) {
            log.error("删除定时任务失败,任务id：{}，备注：{}", existedSysJob.getId(), existedSysJob.getRemark());
            return false;
        } else {
            // 删除成功清除定时任务器中的对应任务
            SchedulingRunnable task = new SchedulingRunnable(
                    existedSysJob.getBeanName(),
                    existedSysJob.getMethodName(),
                    existedSysJob.getMethodParams());
            cronTaskRegistrar.removeCronTask(task);
        }
        return true;
    }

    @Override
    public boolean delByIds(List<Long> ids) {
        if (ids != null){
            ids.forEach(this::del);
        }
        return true;
    }

    @Override
    public boolean changesStatus(Long id, boolean status) {
        ScheduleSetting scheduleSetting = getById(id);
        scheduleSetting.setStatus(status);
        boolean update = updateById(scheduleSetting);
        if (!update) {
            log.error("修改定时任务状态失败,任务id：{}，备注：{}", scheduleSetting.getId(), scheduleSetting.getRemark());
            return false;
        }
        SchedulingRunnable task = new SchedulingRunnable(
                scheduleSetting.getBeanName(),
                scheduleSetting.getMethodName(),
                scheduleSetting.getMethodParams());
        cronTaskRegistrar.removeCronTask(task);
        if (status) {
            cronTaskRegistrar.addCronTask(task, scheduleSetting.getCron());
        }
        return true;
    }
}
